from django.db import models
from pets.models import Pet
from django.utils import timezone


class FoodType(models.Model):
    name = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)
    calories_per_gram = models.FloatField()
    recommended_daily_amount = models.FloatField(help_text="Recommended daily amount in grams")
    pet_types = models.ManyToManyField('pets.PetType')


class FeedingSchedule(models.Model):
    pet = models.ForeignKey(Pet, on_delete=models.CASCADE, related_name='feeding_schedules')
    food_type = models.ForeignKey(FoodType, on_delete=models.SET_NULL, null=True)
    amount = models.FloatField(help_text="Amount in grams")
    times_per_day = models.PositiveIntegerField(default=2)
    specific_times = models.JSONField(default=list, help_text="List of specific feeding times in HH:MM format")
    is_active = models.BooleanField(default=True)

    def next_feeding_time(self):
        now = timezone.now()
        today = now.date()
        times = self.specific_times

        for time_str in times:
            hour, minute = map(int, time_str.split(':'))
            feeding_time = timezone.make_aware(timezone.datetime(today.year, today.month, today.day, hour, minute))
            if feeding_time > now:
                return feeding_time

        # 如果今天的所有时间都已过，返回明天的第一个时间
        tomorrow = today + timezone.timedelta(days=1)
        hour, minute = map(int, times[0].split(':'))
        return timezone.make_aware(timezone.datetime(tomorrow.year, tomorrow.month, tomorrow.day, hour, minute))


class FeedingLog(models.Model):
    pet = models.ForeignKey(Pet, on_delete=models.CASCADE, related_name='feeding_logs')
    schedule = models.ForeignKey(FeedingSchedule, on_delete=models.SET_NULL, null=True)
    food_type = models.ForeignKey(FoodType, on_delete=models.SET_NULL, null=True)
    amount = models.FloatField()
    timestamp = models.DateTimeField(auto_now_add=True)
    consumed_amount = models.FloatField(null=True, blank=True, help_text="Actual amount consumed in grams")
    notes = models.TextField(blank=True)

    def save(self, *args, **kwargs):
        # 自动记录食物类型
        if not self.food_type and self.schedule:
            self.food_type = self.schedule.food_type
        super().save(*args, **kwargs)